package com.darkteam.jhades.cs;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;

import com.darkteam.jhades.common.BaseServerDecoder;
import com.darkteam.jhades.common.BaseServerEncoder;
import com.darkteam.jhades.common.MessageReceivedHandler;
import com.darkteam.jhades.common.message.ResponseMessage;
import com.darkteam.jhades.cs.message.ServerListMessage;
import com.darkteam.jhades.cs.message.ServerNode;

public class ConnectServerPipelineFactory implements ChannelPipelineFactory {
	
	
	@Override
	public ChannelPipeline getPipeline() throws Exception {
		ChannelPipeline pipeline = Channels.pipeline();

		
		// Add the number codec first,
		pipeline.addLast("decoder", new BaseServerDecoder());
		pipeline.addLast("encoder", new BaseServerEncoder());

		// and then business logic.
		// Please note we create a handler for every new channel
		// because it has stateful properties.
		
		ConnectServerHandler connectServerHandler = new ConnectServerHandler();
		
		connectServerHandler.addMessageReceivedHandler(CONSTANTS.SERVER_LIST, new MessageReceivedHandler() {
			
			@Override
			public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
					throws Exception {
				
				ResponseMessage responseMessage = new ResponseMessage(CONSTANTS.SERVER_LIST);
				ServerListMessage serverListMessage = new ServerListMessage();
				responseMessage.setParan(serverListMessage);
				serverListMessage.add(new ServerNode((short)0, (byte)0));				
				e.getChannel().write(responseMessage);
				
			}
		});
		connectServerHandler.addMessageReceivedHandler(CONSTANTS.SERVER_SELECTION, new MessageReceivedHandler() {
			
			@Override
			public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
					throws Exception {
				// TODO Auto-generated method stub
				
			}
		});
		pipeline.addLast("handler", connectServerHandler);

		return pipeline;
	}

}
